package cn.com.callback


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;

import com.alibaba.fastjson.JSONObject
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import groovy.json.*;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import com.alibaba.fastjson.JSONObject
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.sql.Date
import java.text.SimpleDateFormat

import javax.xml.ws.http.HTTPException
import net.sf.json.JSONArray
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory




import java.io.IOException;
 
public class BP_Statisfaction implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(BP_Statisfaction.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){

	def returnDealFlag="";//响应标识 1 成功，0 失败
	def enterpriseId = '7500393';
	def token = '5d0eb907c260fd751a54d91dab942f9b';
	long timestamp =	System.currentTimeMillis() / 1000;
	long strtime = (System.currentTimeMillis() - 30 * 60 * 1000)/1000
	//log.debug("result111:"+strtime);
	//log.debug("2222");
	
	def sign = enterpriseId+timestamp+token;
	try {
		MessageDigest md = MessageDigest.getInstance("MD5")
		md.update(sign.getBytes())//update处理
		byte [] encryContext = md.digest()//调用该方法完成计算

		int i
		StringBuffer buf = new StringBuffer("")
		for (int offset = 0; offset < encryContext.length; offset++) {//做相应的转化（十六进制）
			i = encryContext[offset]
			if (i < 0) i += 256
			if (i < 16) buf.append("0")
		sign = buf.append(Integer.toHexString(i)).toString()
	   }
	   log.debug("32result: " + buf.toString())// 32位的加密
	   log.debug("16result: " + buf.toString().substring(8, 24))// 16位的加密
	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		e.printStackTrace()
	}
	//满意度
	def url  = 'https://api-5.cticloud.cn/interface/v10/investigation/query?validateType=2&enterpriseId='+enterpriseId+'&timestamp='+timestamp+'&sign='+sign+'&limit=100&startTime='+strtime+'&endTime='+timestamp;
	log.debug('接口调用:'+url);
	def result = interfaceUtil(url, "");

	
	if(result.equals('1')){
		returnDealFlag = 0;
		log.debug('接口调用失败');
	}else {
		String cloudResponseStr=result.toString();
		//初步解析获取接口返回状态
		JSONObject reponseBodyJsonObject = JSONObject.parseObject(cloudResponseStr);
		String resultCode = reponseBodyJsonObject.getString("result");
		String resultMsg = reponseBodyJsonObject.getString("description");
		log.debug('resultCode:'+resultCode);
		//接口返回成功，则继续解压里面的内容
		if(resultCode.equals('0')) {
		//JSONObject cloudConfigList = JSONObject.parseArray(reponseBodyJsonObject.getString("data"));
		def cloudConfigList =[];
		 cloudConfigList = reponseBodyJsonObject.getJSONArray("data");
		log.debug('cloudConfigList:'+cloudConfigList);
		if (cloudConfigList.size() > 0) {
		//定义时间戳转时间格式
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
				//开始解析内容
			for (int a = 0;a<cloudConfigList.size();a++) {
				//电话唯一标识id
				String mainUniqueId = cloudConfigList.getJSONObject(a).("mainUniqueId");
				//满意度调查时的通话类型
				String callType = cloudConfigList.getJSONObject(a).("callType");
				//热线号码
				String hotline = cloudConfigList.getJSONObject(a).("hotline");
				//客户号码，国内固话或手机
				String customerNumber = cloudConfigList.getJSONObject(a).("customerNumber");
				//座席工号
				String cno = cloudConfigList.getJSONObject(a).("cno");
				//座席姓名
				String agentName = cloudConfigList.getJSONObject(a).("agentName");
				//座席crm_id
				String agentCrmId = cloudConfigList.getJSONObject(a).("agentCrmId");
				//开始满意度调查时间
				String startTime = sdf.format(new Date(Long.valueOf(cloudConfigList.getJSONObject(a).("startTime")+"000")));
				//结束满意度调查时间
				String endTime = sdf.format(new Date(Long.valueOf(cloudConfigList.getJSONObject(a).("endTime")+"000")));
				//持续时长秒数
				String duration = cloudConfigList.getJSONObject(a).("duration");
				//满意度调查结果，客户按键值
				String keys = cloudConfigList.getJSONObject(a).("keys");
				//满意度调查时的通话类型
				String createTime = sdf.format(new Date(Long.valueOf(cloudConfigList.getJSONObject(a).("createTime"))));
				
				log.debug('mainUniqueId:'+mainUniqueId);
				int flag1 = duplicate_removal(mainUniqueId,eliteBean);
				if(flag1<1){
				eliteBean.update("insert into BP_Statisfaction(mainUniqueId,callType,hotline,customerNumber,cno,agentName,agentCrmId,startTime,endTime,duration,keys,createTime)"+
				"values ('"+mainUniqueId+"','"+callType+"','"+hotline+"','"+customerNumber+"','"+cno+"','"+agentName+"','"+agentCrmId+"','"+startTime+"','"+endTime+"','"+duration+"','"+keys+"','"+createTime+"')","dataSource")
				}
				
			}
			returnDealFlag = 1;
			//println('写入完成');
				}
			}else {
				returnDealFlag = 0;
				//println('接口返回 失败');
				
			}
		}
			return returnDealFlag;
	}
	
	
	//调用天润接口，返回接口获取信息
		static Object interfaceUtil(String path,String data) throws Exception   {
		String str=new String();
		str = '222';
		try {
			URL url = new URL(path)
			//打开和url之间的连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection()
			PrintWriter out = null
			
			/**设置URLConnection的参数和普通的请求属性****start***/
		   
			conn.setRequestProperty("accept", "*/*")
			conn.setRequestProperty("connection", "Keep-Alive")
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)")
			
			/**设置URLConnection的参数和普通的请求属性****end***/
			
			//设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
			//最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
			//post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
			conn.setDoOutput(true)
			conn.setDoInput(true)
			
			conn.setRequestMethod("GET")//GET和POST必须全大写
			/**GET方法请求*****start*/
			/**
			 * 如果只是发送GET方式请求，使用connet方法建立和远程资源之间的实际连接即可；
			 * 如果发送POST方式的请求，需要获取URLConnection实例对应的输出流来发送请求参数。
			 * */
			conn.connect()
			
			/**GET方法请求*****end*/
			
			/***POST方法请求****start*/
			
			/*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流
			
			out.print(data);//发送请求参数即数据
			
			out.flush();//缓冲数据
			*/
			/***POST方法请求****end*/
			
			//获取URLConnection对象对应的输入流
			InputStream is = conn.getInputStream()
			//构造一个字符流缓存
			BufferedReader br = new BufferedReader(new InputStreamReader(is))
			
			while ((str = br.readLine()) != null) {
				str=new String(str.getBytes(),"UTF-8")//解决中文乱码问题
				//System.out.println(str);
				return str;
			}
			//关闭流
			is.close()
			//断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
			//固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
			conn.disconnect();
			
			System.out.println("完整结束")
		} catch (Exception e) {
			e.printStackTrace()
			return '1';
		}
		
	}
	
	static Object  duplicate_removal(String guid,EliteBean eliteBean) throws Exception{
		def returnsql=eliteBean.chaxun_sql("select count(*) as num from BP_Statisfaction cd where cd.mainUniqueId='"+guid+"'","dataSource");
		def returnstring = returnsql[0];
		def ngsFSUrl=returnstring.get("num");
		return ngsFSUrl;
	}
			   
	
}